package cn.wx.api.impl;

import cn.wx.api.WxOpenMultipleService;
import lombok.experimental.Delegate;
import me.chanjar.weixin.open.api.WxOpenService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

/**
 * 多公众平台实现
 *
 * @author: sunshaoping
 * @date: Create by in 1:35 下午 2020/5/23
 */
public class WxOpenMultipleServiceImpl implements WxOpenMultipleService, ApplicationListener<ContextRefreshedEvent> {

    @Delegate
    private WxOpenService wxOpenService;

    private final String defName;
    private ApplicationContext applicationContext;

    public WxOpenMultipleServiceImpl(String defName) {
        this.defName = defName;
    }

    @Override
    public WxOpenService switchoverTo(String name) {
        if (this.applicationContext.containsBean(name)) {
            return applicationContext.getBean(name, WxOpenService.class);
        }
        throw new IllegalArgumentException(String.format("无法找到对应【%s】的配置信息，请核实！", name));
    }


    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        this.applicationContext = event.getApplicationContext();
        this.wxOpenService = applicationContext.getBean(defName, WxOpenService.class);
    }
}
